# ip生成及存入文件
def ip_create():
    import random
    import json
    global ipshow
    ipshow = 0

    with open("ips.txt", "w+") as fp:
        for i in range(1000):
            str1 = random.randint(1, 256)
            ip = f'172.25.254.{str1}'
            ips = json.dumps(ip)
            fp.write(ip + '\n')

    with open("ips.txt", "r+") as fp:
        ipshow = fp.read()


# 存储ip放在一个列表里
def ip_get():
    global ip_end
    global ip_list
    ip_list = []
    ip_end = ''

    # 根据换行符，将每个ip切割为一组list
    lst1 = ipshow.split("\n")
    for i in lst1:
        # 去除最后一个空的换行
        if i == '':
            pass
        else:
            # 将所有ip存入列表里
            ip_list.append(i)


# 排序ip生成次数
def ip_sort():
    global dict1
    global ipsort
    dict1 = {}
    ipsort = []

    for i in ip_list:
        # 计数ip出现次数
        j = ip_list.count(i)
        # i为ip，j为ip出现次数，存入字典中
        dict2 = {i: j}
        dict1.update(dict2)
    # 依据value值的大小进行降序
    ipsort = sorted(dict1.items(), key=lambda x: x[1], reverse=True)


# 获取前十名
def get_top_ten():
    print("ip出现频率为前十的ip为：")
    # 从按照次数出现最多的ip字典里取出前十
    for i in range(10):
        print(f"{ipsort[i][0]}出现{ipsort[i][1]}次")


def main():
    ip_create()
    ip_get()
    ip_sort()
    get_top_ten()


main()
